#!/bin/bash

# 获取最新版本的docker-compose
echo "正在获取最新版本的docker-compose..."

# 获取最新版本号
VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')

if [ -z "$VERSION" ]; then
    echo "无法获取最新版本信息，使用默认版本v2.20.2"
    VERSION="v2.20.2"
fi

echo "安装版本: $VERSION"

# 创建临时文件
TMP_FILE=$(mktemp)

# 下载docker-compose
echo "正在下载docker-compose $VERSION..."
if curl -L "https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o "$TMP_FILE"; then
    echo "下载完成，正在安装..."
    
    # 移动文件到目标位置
    if sudo mv "$TMP_FILE" /usr/local/bin/docker-compose; then
        # 添加执行权限
        if sudo chmod +x /usr/local/bin/docker-compose; then
            echo "权限设置成功"
        else
            echo "设置执行权限失败"
            exit 1
        fi
    else
        echo "移动文件失败"
        exit 1
    fi
else
    echo "下载失败!"
    rm -f "$TMP_FILE"
    exit 1
fi

# 验证安装
if command -v docker-compose &> /dev/null
then
    echo "docker-compose 安装成功!"
    docker-compose --version
else
    echo "docker-compose 安装失败!"
    exit 1
fi